var Main = window;
var Ext = {
	CONFIG: {
		PlugVersion: "v7"
	}
};
Ext.Home = (function(){
    return {
        Yao: function(take_token, success){
            var url = "?ct=ajax_user&ac=pick_space&token=" + take_token;
            Ext.Plug.Load("random", {
                url: url,
                Success: function(){
                    Core.SpaceData.Sync();
                    //改变按钮样式
                    if(success){
                        success();
                    }
                },
                LoadComplete: function(dom){
                    Util.Mouse.MoveBox({
                        ClickBox: dom,
                        Box: dom,
                        Outer: $(document.body)
                    });
                    dom.css({"top": "-99999px"}).show();
                    window.setTimeout(function(){
                        Util.Layer.Center(dom);
                    },10);
                }
            })
        },
        NewUser: function(){
            PAGE_HELP_KEYS["upload_id"] = "js_upload_fup_box";
            PAGE_HELP_KEYS["frametop_id"] = "js_frame_nav_top";
            Ext.Home.OpenGuide(PAGE_HELP_KEYS);
            return;
            window.setTimeout(function(){
                Ext.Plug.Load("help_box");
            },10);
        },
        OpenGuide: function(setting){
            window.setTimeout(function(){
                Ext.Plug.Load("novice_guide", setting);
            }, 10);
        }
    }
})()

Ext.Plug = (function(){
	var _loadLog = {};
	
	return {
		Load: function(key, settings){
			if(_loadLog[key]){
				try{
					Plug[key].Load(settings);
				}catch(e){};
				return;
			}
			_loadLog[key] = true;
			
			var js = 'statics/web/plug/' + key + '/' + key + '.js?v=' + Ext.CONFIG.PlugVersion;
			var css = 'statics/web/plug/' + key + '/css/' + key + '.css?v=' + Ext.CONFIG.PlugVersion;
			if(!settings){
				settings = {};
			}
			settings.css = css;
            
			Util.Load.JS(js, function(){
				try{
					Plug[key].Load(settings);
                    
				}catch(e){};
			});
		}
	}
})()

var TreeCTL = {
    _ac_obj: {aid: -1, cid: 0},
    GetActive: function(){
        return TreeCTL._ac_obj;
    },
    Select: function(aid, cid){
        TreeCTL._ac_obj.aid = aid;
        TreeCTL._ac_obj.cid = cid;
        TreeCTL.DeFocusNode();
        var treeBox = $("#js_left_side_box");
        var a = treeBox.find("[aid='"+aid+"']");
        if(a.length){
            a.addClass("focus");
            return false;
        }
        return false;
    },
    DeFocusNode: function(){
        $("#js_side_main_box").find("a.focus").removeClass("focus");
    },
    GetParents: function(cid){

        return Core.Tree.GetParents(cid, true);
    },
    GetItem: function(cid){
        return Core.Tree.GetItem(cid);
    },
    Init: function(){
        Core.Dir.AddDoHandler({
            AddNode: function(r){
                Core.Tree.GetItem(r.cid, function(n){
                    var node = n;
                    //PageCTL.GOTO(node.aid, node.cid);
                    if(!r["not_refresh"]){
                        PageCTL.GOTO(node.aid, node.cid); 
                    }
                });
            },
            RenameNode: function(r){
                var node = Core.Tree.GetItem(r.cid);
                var par = Core.Tree.GetItem(node.pid);
                var acCid = Core.FileConfig.cid;
                var acAid = Core.FileConfig.aid;
                if(acCid == 0){
                    acCid = acAid + "_0";
                }

                if(par.aid == acAid && par.cid == acCid){
                    //PageCTL.Refresh();

                    if(Core.FileConfig.DataAPI) Core.FileConfig.DataAPI.UpdateDir({
                        cid: r.cid, 
                        dir_name: r.cname
                    });
                }
            },
            DeleteNode: function(r){
                var par = Core.Tree.GetItem(r.pid);
                if(par.cid && par.cid.toString().indexOf("_0") != -1){
                    par.cid = 0;
                }
                //PageCTL.GOTO(par.aid, par.cid);
                Core.CountSync.Sync();
            }
        })
        
        
        var PageIframe = document.getElementById("js_iframe_list");
        $(PageIframe).bind("readystatechange",function(){
            if(this.readyState == "complete" || this.readyState == "loaded"){
                var OldUrlCookie = "page_oldurl_cook";
                var url = this.contentWindow.location.href;
                Util.Cookie.set(OldUrlCookie, url);
                if(/^.*(ct=index&ac=home).*$/.test(url)){
                    
                    TreeCTL._ac_obj.aid = -1;
                    TreeCTL._ac_obj.cid = 0;
                }
            }
        }).bind("load",function(){
            var OldUrlCookie = "page_oldurl_cook";
            var url = this.contentWindow.location.href;
            Util.Cookie.set(OldUrlCookie, url);
            if(/^.*(ct=index&ac=home).*$/.test(url)){
                TreeCTL._ac_obj.aid = -1;
                TreeCTL._ac_obj.cid = 0;
            }
        })
    }
};
//页面控制器
var PageCTL = {
    GOTO_MAP: function(type, ids, loc){
        var url = PAGE_PATHS["MY"] + "/index.php?r=List/index&aid=35&tpl=" + type + "_pg&flag=-1&loc=" + loc + "&ids=" + ids;
        PageCTL.GOTO_URL(url);
    },
    ChangeMode: function(type){
        var acObj = TreeCTL.GetActive();
        if(acObj){
            if(Number(acObj.aid) == 3){
                Util.Cookie.set("list_view_img_mod", type, 24 * 30 * 12);
            }
            else{
                Util.Cookie.set("list_view_other_mod", type, 24 * 30 * 12);
            }
        
            PageCTL.GOTO(acObj.aid, acObj.cid);
        }
    },
    GOTO: function(aid, cid){
        cid = cid.toString().indexOf("_0") != -1? 0 : cid;
        var tpl = "list";
        var mod = Util.Cookie.get("list_view_other_mod");
        
        
        if(mod && (mod == "list" || mod == "view" || mod=="view_large")){
            tpl = mod;
        }
        
        if(Number(aid) == 3){
            var photoView = Util.Cookie.get("list_view_img_mod");
            if(!photoView){
                tpl = "view";
            }
            else{
                tpl = photoView;
            }
            
        }
        tpl += "_pg";
        var page_count = SCREEN_PARAM.page_count?SCREEN_PARAM.page_count:30;
        
        var url = PAGE_PATHS["MY"]+"/index.php?r=list/index&ct=file&ac=userfile&aid=" + aid + "&cid=" + cid + "&tpl=" + tpl + "&limit=" + page_count;
        
        $("#js_iframe_list").attr("src", url);
        
    },
    GOTO_URL: function(url){
        TreeCTL.DeFocusNode();
        $("#js_iframe_list").attr("src", url);
    },
    Refresh: function(){
        $("#js_iframe_list")[0].contentWindow.location.reload();
    },
    SelectNode: function(aid, cid){
        if(!TreeCTL.Select(aid, cid)){
            var bottomBox = $("#js_left_bottom_box");
            bottomBox.find(".focus").removeClass("focus");
            var ele = bottomBox.find("[aid='"+aid+"']");
            if(ele.length){
                ele.addClass("focus");

            }
        }
    },
    CreateDir: function(aid, cid){
        Core.Dir.Create(aid, cid);
    },
    MarkURL: function(url){
        var OldUrlCookie = "page_oldurl_cook";
        Util.Cookie.set(OldUrlCookie, url);
    }
}

var PageFrameCtl = (function(){
    var _cache = {};
    var hash = window.location.hash;
    if(hash.replace("#","") == "help"){
        _cache.not_open_new_user = true;
    }
    return {
        Invite: function(){
            if(!_cache.InviteFrame){
                var con = $('<div style="">'+
                        '<iframe src="'+PAGE_PATHS.MY_OS+'/?ct=invite" frameborder="0" rel="frame" style="width:800px; height:530px;"></iframe>'+
                     '</div>');
                _cache.InviteFrame = new Core.DialogBase({
                    title: '邀请好友', 
                    content: con, 
                    width: 800,
                    height: 630
                });

            }
            _cache.InviteFrame.Open();
        },
        NewUser: function(){
            if(_cache.not_open_new_user) return;
            if(!_cache.NewUserFrame){
                var con = $('<div style="">'+
                        '<iframe src="'+PAGE_PATHS.PASSPORT+'/?ac=guide&app=u" frameborder="0" rel="frame" style="background:#fff;width:800px; height:530px;"></iframe>'+
                     '</div>');
                _cache.NewUserFrame = new Core.DialogBase({
                    title: '完善个人资料', 
                    content: con, 
                    width: 800,
                    height: 630
                });

            }
            _cache.NewUserFrame.Open();
        },
        HideNewUser: function(){
            if(_cache.NewUserFrame){
                _cache.NewUserFrame.Close();
            }
        }

    }
})();

//路径控制
var URL_CTL = {
    _cache: {},
    _selectTab: function(key, gourl){
        var conbox = $("#js_frame_contain");
        var navTop = $("#js_frame_nav_top");
        //conbox.find("iframe").hide();
        $("#js_frame_box").hide();
        conbox.find("#js_add_frame_box").hide();
        conbox.find("#js_other_frame_box").hide();

        navTop.find("[t]").removeClass("focus");
        var otherFrame = $("#js_other_frame_box");
        navTop.find("[t='"+key+"']").addClass("focus");
        Util.Cookie.set("cache_index_tab", key);
        switch(key){
            case "u":
                $("#js_frame_box").show();
                break;
            case "favorite":
                $("#js_frame_box").show();
                break;
            case "app":
                $("#js_add_frame_box").show();
                break;
            default:
                var frame = document.getElementById("js_other_frame_box");
                $(frame).show();
                var url;
                var changeState = false;
                switch(key){
                    case "q":
                        url = gourl? gourl : PAGE_PATHS.Q + '/?_t=' + new Date().getTime();
                        URL_CTL._cache.old_q_url = url;
                        Util.Cookie.set("cache_q_url", url);
                        break;
                    case "my":
                        url = gourl? gourl : PAGE_PATHS.MY + '/?ct=friend&type=manage&_t=' + new Date().getTime();
                        URL_CTL._cache.old_my_url = url;
                        Util.Cookie.set("cache_my_url", url);
                        break;
                    case "wan":
                        url = gourl? gourl : PAGE_PATHS.WAN + '/?_t=' + new Date().getTime();
                        URL_CTL._cache.old_wan_url = url;
                        Util.Cookie.set("cache_wan_url", url);
                        break;
                    case "downLoad":
                        url = gourl? gourl : PAGE_PATHS.DOWNLOAD + '/?_t=' + new Date().getTime();
                        URL_CTL._cache.cache_download_url = url;
                        Util.Cookie.set("cache_download_url", url);
                        break;
                    case "account":
                        url = gourl? gourl : PAGE_PATHS.ACCOUNT + '/?_t=' + new Date().getTime();
                        URL_CTL._cache.cache_account_url = url;
                        Util.Cookie.set("cache_account_url", url);
                        break;
                }
                if($(frame).attr("not_url") == "1"){
                    changeState = true;
                    $(frame).removeAttr("not_url");
                }
                else{
                    if(URL_CTL._cache.OldOtherKey != key || gourl){
                        changeState = true;
                    }
                }
                URL_CTL._cache.OldOtherKey = key;
                if(changeState){
                    frame.src = url;
                }
                break;
        }
    },
    OtherChange: function(url){
        switch(URL_CTL._cache.OldOtherKey){
            case "q":
                URL_CTL._cache.old_q_url = url;
                Util.Cookie.set("cache_q_url", url);
                break;
            case "my":
                URL_CTL._cache.old_my_url = url;
                Util.Cookie.set("cache_my_url", url);
                break;
            case "wan":
                URL_CTL._cache.old_wan_url = url;
                Util.Cookie.set("cache_wan_url", url);
                break;
        }
    },
    Home: function(){
        var activeKey = Util.Cookie.get("cache_index_tab");
        URL_CTL._selectTab("u");
        var framebox = $("#js_frame_box").find("iframe");
        if(activeKey == "u" || framebox.attr("not_url") == "1"){
            TreeCTL.DeFocusNode();
            Util.Cookie.set("page_oldurl_cook", "");
            $(framebox).removeAttr("not_url");
            framebox.attr("src",PAGE_PATHS["MY"]+"/index.php?r=netdisk/homepage&_t=" + new Date().getTime());
        }
    },
    MyFile: function(){
    	//进行进度信息的请求
    	Core.SpaceData.Sync(function(){
        	Core.SpaceTop.Modify();
        });
        URL_CTL._selectTab("u");
        var framebox = $("#js_frame_box").find("iframe");
        TreeCTL.DeFocusNode();
        Util.Cookie.set("page_oldurl_cook", "");
        $(framebox).removeAttr("not_url");
        framebox.attr("src",PAGE_PATHS["MY"]+"/index.php?r=netdisk/homepage&_t=" + new Date().getTime());
    },
    GOTO: function(aid, cid){
        URL_CTL._selectTab("u");
        var ifr = $("#js_frame_box").find("iframe");
        if(ifr.attr("not_url") == "1"){
            ifr.removeAttr("not_url");
        }
        PageCTL.GOTO(aid, cid);
    },
    Game: function(){
        var url;
        if(Util.Cookie.get("cache_index_tab") == "wan"){
            var cache_gurl = Util.Cookie.get("cache_wan_url");
            if(cache_gurl){
                url = cache_gurl;
            }
        }
        URL_CTL._selectTab("wan", url);
    },
    My: function(params){
        var url;

        var url;
        if(params){
            url = PAGE_PATHS.MY + '/?'+ params;
        }
        else{
            if(Util.Cookie.get("cache_index_tab") == "my"){
                var cache_gurl = Util.Cookie.get("cache_my_url");
                if(cache_gurl){
                    url = cache_gurl;
                }
            }
        }


        URL_CTL._selectTab("my", url);
    },
    G: function(params){
        var url;
        if(params){
            url = PAGE_PATHS.Q + '/' + params + '/?_t=' + new Date().getTime();
        }
        else{
            if(Util.Cookie.get("cache_index_tab") == "q"){
                var cache_gurl = Util.Cookie.get("cache_q_url");
                if(cache_gurl){
                    url = cache_gurl;
                }
            }
        }
        URL_CTL._selectTab("q", url);
    },
    App: function(){
        URL_CTL._selectTab("app");
        var appFrame = document.getElementById("js_add_frame_box");
        if($(appFrame).attr("not_url") == "1"){
            $(appFrame).removeAttr("not_url")
            appFrame.src = PAGE_PATHS["MY"]+"/index.php?ac=app&_t=" + new Date().getTime();
        }

    },
    Favorite: function(){
        var activeKey = Util.Cookie.get("cache_index_tab");
        URL_CTL._selectTab("favorite");
        var framebox = $("#js_frame_box").find("iframe");
        TreeCTL.DeFocusNode();
        Util.Cookie.set("page_oldurl_cook", "");
        $(framebox).removeAttr("not_url");
        framebox.attr("src",PAGE_PATHS["MY"]+"/index.php?r=list/index&ct=file&ac=userfile&aid=31&cid=0&tpl=list_pg&limit=45&_t=" + new Date().getTime());
    },
    Account: function(){
        URL_CTL._selectTab("account");
//        var appFrame = document.getElementById("js_add_frame_box");
//        if($(appFrame).attr("not_url") == "1"){
//            $(appFrame).removeAttr("not_url")
//            appFrame.src = PAGE_PATHS["MY"]+"/index.php?r=setting/index&_t=" + new Date().getTime();
//        }
    },
    DownLoad: function(){
        URL_CTL._selectTab("downLoad");
//        var appFrame = document.getElementById("js_add_frame_box");
//        if($(appFrame).attr("not_url") == "1"){
//            $(appFrame).removeAttr("not_url")
//            appFrame.src = PAGE_PATHS["MY"]+"/index.php?r=site/download&_t=" + new Date().getTime();
//        }
    },
    GetCacheMainURL:function(){
        var OldUrlCookie = "page_oldurl_cook";
        var PageOldUrl = Util.Cookie.get(OldUrlCookie);
        if(!PageOldUrl || PageOldUrl=="undefined"){
            PageOldUrl = PAGE_PATHS["MY"]+"/index.php?r=netdisk/homepage";
        }
        return PageOldUrl;
    },
    Setting: function(){
        URL_CTL._selectTab("u");
        var ifr = document.getElementById("js_frame_box");
        if($(ifr).attr("not_url") == "1"){
            $(ifr).removeAttr("not_url");
            ifr.src = "?ct=index&ac=home&_t=" + new Date().getTime();
            ifr.onload = (function(){
                window.setTimeout(function(){
                   PageCTL.GOTO_URL("?ac=setting&_t=" + new Date().getTime());
                }, 100);
            })
            ifr.onreadystatechange = (function(){
                if(this.readyState == "complete"){
                    PageCTL.GOTO_URL("?ac=setting&_t=" + new Date().getTime());
                }
            });
        }
        else{
            if(ifr){
                PageCTL.GOTO_URL("?ac=setting&_t=" + new Date().getTime());
            }
        }
    }
}